There are lot of info to check for "undefined" normal vars in JavaScript, but I need to check for an eval(var) like:
var Hello_0 = "Hello 0 !";
console.log(" Hello_0 is: " + eval("Hello_"+0));
var dinamyc_var = "Hello_"+1;
//None of the next conditionals is triggered///
if (eval(dinamyc_var) === undefined) {
console.log(" dinamyc_var is undefined ");
}
if (eval(dinamyc_var) === null) {
console.log(" dinamyc_var is null ");
}
if ( typeof eval(created_node) === undefined ) {
console.log(" dinamyc_var is typeof undefined ");
}
if ( typeof eval(created_node) === null ) {
console.log(" dinamyc_var is typeof null ");
}
console.log(" dinamyc_var is: " + eval(dinamyc_var));
https://jsfiddle.net/mczdrv5t/
The console show the value of eval("Hello_"+0) because was declared, but the console show the next error when try to call eval("Hello_"+1) that not was declared. I need to handle possible undeclared vars.
Uncaught ReferenceError: Hello_1 is not defined at eval (eval at ....
Don't use eval. If you need to store values of varying names, use an object instead:
const values = {}
values["Hello_0"] = "Hello 0 !"
if (values["Hello_" + 1] === undefined) {
// ...
}
As a sidenote, if (eval('typeof ' + dynamic_var) === 'undefined') would work but again, don't use eval.
Don't do window[dynamic_var] = ... to store global variables either, the names might clash with existing globals.